import Vue from "vue";
import Router from "vue-router";
Vue.use(Router);
const loadRoutes = files =>
  files
    .keys()
    .reduce((arr, key) => {
      const routes = files(key).default;
      return typeof routes === "object" ? arr.concat(routes) : arr;
    }, [])
    .sort((prev, next) => (prev.sort || 0) - (next.sort || 0));

let routes = [
  {
    path: "/",
    name: "home",
    meta: {
      title: "首页",
      keepAlive: true,
    },
    redirect: "/home",
    component: () => import("views/Home.vue"),
    children: loadRoutes(require.context("./home", false, /\.js$/)),
  },
  {
    path: "/404",
    name: "404",
    component: () => import("views/404.vue"),
    meta: {
      title: "404",
      keepAlive: true,
    },
  }
];

// 获取文件下所有路由
const routerContext = require.context("./", true, /\.js$/);
routerContext.keys().forEach(route => {
  // 如果是根目录的 index.js 、不处理
  if (route.startsWith("./index")) {
    return;
  }
  const routerModule = routerContext(route);
  /**
   * 兼容 import export 和 require module.export 两种规范
   */
  routes = routes.concat(routerModule.default || routerModule);
});
routes = routes.concat({
  path: "*",
  redirect: "/404",
});
console.log(routes);
const createRouter = () =>
  new Router({
    // mode: 'history', // require service support
    // 配置url 默认添加项 process.env.BASE_URL
    // mode: "history",
    base: process.env.BASE_URL,
    routes,
  });
const myRouter = createRouter();

export function resetRouter() {
  myRouter.replace({
    name: "login",
  });
}
export default myRouter;
